<template>
  <Form
    class="xtx-form"
    ref="formComp"
    :validation-schema="veeValidateSchema"
    v-slot="{ errors }"
  >
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-user"></i>
        <Field
          v-model="form.accountApi"
          name="accountApi"
          class="input"
          type="text"
          placeholder="请输入用户名"
        />
      </div>
      <div class="error">{{ errors.accountApi }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field
          v-model="form.mobile"
          name="mobile"
          class="input"
          type="text"
          placeholder="请输入手机号"
        />
      </div>
      <div class="error">{{ errors.mobile }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field
          v-model="form.code"
          name="code"
          class="input"
          type="text"
          placeholder="请输入验证码"
        />
        <span class="code" @click="sendCode">
          {{ time === 0 ? "发送验证码" : `${time}秒后开始` }}
        </span>
      </div>
      <div class="error">{{ errors.code }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field
          v-model="form.password"
          name="password"
          class="input"
          type="password"
          placeholder="请输入密码"
        />
      </div>
      <div class="error">{{ errors.password }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field
          v-model="form.rePassword"
          name="rePassword"
          class="input"
          type="password"
          placeholder="请确认密码"
        />
      </div>
      <div class="error">{{ errors.rePassword }}</div>
    </div>
    <a href="javascript:;" class="submit" @click="QQLogin">立即提交</a>
  </Form>
</template>

<script>
import veeValidateSchema from '@/utils/vee-validate-schema'
import { Form, Field } from 'vee-validate'
import { reactive, ref, onUnmounted, inject } from 'vue'
import { useIntervalFn } from '@vueuse/core'
import { userQQPatchCode, userQQPatchLogin } from '@/api/user.js'
import Message from '@/components/library/Message.js'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
export default {
  name: 'CallbackPatch',
  components: {
    Form,
    Field
  },
  setup () {
    // 表单信息
    const form = reactive({
      accountApi: '',
      mobile: '',
      code: '',
      password: '',
      rePassword: ''
    })

    const store = useStore()
    const router = useRouter()

    // 设置定时器
    const time = ref(0)
    const { resume, pause } = useIntervalFn(
      () => {
        time.value--
        if (time.value <= 0) {
          pause()
        }
      },
      1000,
      { immediate: false }
    )

    // 卸载组件时清除定时器
    onUnmounted(() => {
      pause()
    })

    // 发送验证码
    const sendCode = async () => {
      try {
        // 发请求 -- 参数：手机号
        const res = await userQQPatchCode(form.mobile)
        console.log(res)
        // 计时器时间从60开始
        time.value = 60
        // 启动定时器
        resume()
        // 提示
        Message({ type: 'success', message: '发送成功' })
      } catch (error) {
        Message({ type: 'warn', message: error.response.data.message })
      }
    }

    const qqUserInfo = inject('qqUserInfo')
    const id = qqUserInfo.value.openId

    const formComp = ref(null)
    // 提交按钮
    const QQLogin = async () => {
      const validateResult = await formComp.value.validate()
      try {
        if (validateResult) {
          // 发请求 -- 参数：unionId, mobile, code, account, password
          const { result: userInfo } = await userQQPatchLogin({
            unionId: id,
            ...form
          })
          // 存储信息
          store.commit('user/setUser', userInfo)
          // 跳转
          router.push(store.state.user.redirectUrl)
          Message({ type: 'success', message: '登录成功' })
          // 合并购物车
          store.dispatch('cart/mergeLocalCart')
        } else {
          Message({ type: 'warn', message: '验证失败' })
        }
      } catch (error) {
        Message({ type: 'warn', message: '用户名或手机号已存在' })
      }
    }

    return { veeValidateSchema, form, sendCode, time, QQLogin, formComp }
  }
}
</script>

<style scoped lang='less'>
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
